package com.wangsai.framework.supersecurity.satoken;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.wangsai.framework.supersecurity.client.UserStore;
import com.wangsai.framework.supersecurity.core.UserRequest;
import com.wangsai.framework.supersecurity.core.context.chain.UserContextFilter;
import com.wangsai.framework.supersecurity.core.context.chain.UserContextFilterChain;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;


/**
 * @author Mr.Wang
 * @date 2021-08-14 16:16
 */
@Slf4j
@AllArgsConstructor
public class SaUserContextFilter implements UserContextFilter {

    private final UserStore userStore;

    @Override
    public void doFilter(UserRequest userRequest, UserContextFilterChain filterChain) {
        if (!userRequest.isHasUser() && RequestContextHolder.getRequestAttributes() != null && StpUtil.isLogin()) {
            try {
                Object user = userStore.get(userRequest.getUser().getClass());
                userRequest.getUser().putAll(BeanUtil.beanToMap(user, false, true));
                userRequest.setHasUser(true);
            } catch (ClassCastException exception) {
                log.warn("用户类型转换出错");
            }
        }
        filterChain.doFilter(userRequest, filterChain);
    }
}